#!/bin/bash
# ============================================================================
# CentOS 7 配置阿里云镜像源并更新系统
# ============================================================================
#
# 功能说明：
#   1. 备份原有的 yum 仓库配置
#   2. 配置 CentOS 7 使用阿里云镜像源
#   3. 更新 yum 缓存
#   4. 更新系统软件包
#
# 使用方法：
#   sudo ./tools/update_centos7_aliyun.sh
#
# 注意事项：
#   - 需要 root 权限
#   - 仅适用于 CentOS 7.x
#   - 会备份原有配置到 /etc/yum.repos.d/backup/
#
# ============================================================================

set -e
set -u

# 颜色输出
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m'

# 日志函数
log_info() {
    echo -e "${BLUE}[INFO]${NC} $1"
}

log_success() {
    echo -e "${GREEN}[SUCCESS]${NC} $1"
}

log_warning() {
    echo -e "${YELLOW}[WARNING]${NC} $1"
}

log_error() {
    echo -e "${RED}[ERROR]${NC} $1"
}

# 检查是否为 root 用户
if [ "$EUID" -ne 0 ]; then
    log_error "此脚本需要 root 权限"
    log_info "请使用: sudo $0"
    exit 1
fi

# 检查系统类型
if [ ! -f /etc/redhat-release ]; then
    log_error "此脚本仅适用于 CentOS/RHEL 系统"
    exit 1
fi

# 检查是否为 CentOS 7
CENTOS_VERSION=$(rpm -q --qf "%{VERSION}" $(rpm -q --whatprovides redhat-release) 2>/dev/null || echo "")
if [ -z "$CENTOS_VERSION" ]; then
    # 尝试从 /etc/redhat-release 读取
    if grep -q "CentOS Linux release 7" /etc/redhat-release 2>/dev/null; then
        CENTOS_VERSION="7"
    else
        log_error "无法确定 CentOS 版本，或不是 CentOS 7"
        log_info "系统信息: $(cat /etc/redhat-release 2>/dev/null || echo '未知')"
        exit 1
    fi
fi

if [ "$CENTOS_VERSION" != "7" ]; then
    log_warning "检测到 CentOS 版本: $CENTOS_VERSION"
    log_warning "此脚本专为 CentOS 7 设计，继续执行可能不兼容"
    read -p "是否继续? (y/N): " -n 1 -r
    echo
    if [[ ! $REPLY =~ ^[Yy]$ ]]; then
        log_info "已取消"
        exit 0
    fi
fi

log_info "=========================================="
log_info "CentOS 7 配置阿里云镜像源并更新系统"
log_info "=========================================="
log_info "系统版本: $(cat /etc/redhat-release)"
log_info ""

# 阿里云镜像源配置
ALIYUN_BASE_URL="https://mirrors.aliyun.com/centos"
ALIYUN_EPEL_URL="https://mirrors.aliyun.com/epel"

# 备份目录
BACKUP_DIR="/etc/yum.repos.d/backup"
TIMESTAMP=$(date +%Y%m%d_%H%M%S)

# 创建备份目录
log_info "步骤 1/5: 备份原有 yum 仓库配置..."
if [ ! -d "$BACKUP_DIR" ]; then
    mkdir -p "$BACKUP_DIR"
fi

# 备份现有仓库文件
if ls /etc/yum.repos.d/*.repo >/dev/null 2>&1; then
    BACKUP_SUBDIR="$BACKUP_DIR/backup_$TIMESTAMP"
    mkdir -p "$BACKUP_SUBDIR"
    cp -a /etc/yum.repos.d/*.repo "$BACKUP_SUBDIR/" 2>/dev/null || true
    log_success "✅ 已备份到: $BACKUP_SUBDIR"
else
    log_warning "⚠️  未找到需要备份的仓库文件"
fi

# 禁用所有现有仓库（重命名）
log_info "步骤 2/5: 禁用现有仓库配置..."
for repo_file in /etc/yum.repos.d/*.repo; do
    if [ -f "$repo_file" ]; then
        mv "$repo_file" "${repo_file}.bak" 2>/dev/null || true
    fi
done
log_success "✅ 已禁用现有仓库配置"

# 配置阿里云 CentOS 7 基础仓库
log_info "步骤 3/5: 配置阿里云镜像源..."

# 基础仓库配置
cat > /etc/yum.repos.d/CentOS-Base.repo <<'EOF'
[base]
name=CentOS-$releasever - Base - mirrors.aliyun.com
failovermethod=priority
baseurl=https://mirrors.aliyun.com/centos/$releasever/os/$basearch/
        https://mirrors.aliyun.com/centos/$releasever/updates/$basearch/
        https://mirrors.aliyun.com/centos/$releasever/extras/$basearch/
gpgcheck=1
gpgkey=https://mirrors.aliyun.com/centos/RPM-GPG-KEY-CentOS-7
enabled=1

[updates]
name=CentOS-$releasever - Updates - mirrors.aliyun.com
failovermethod=priority
baseurl=https://mirrors.aliyun.com/centos/$releasever/updates/$basearch/
gpgcheck=1
gpgkey=https://mirrors.aliyun.com/centos/RPM-GPG-KEY-CentOS-7
enabled=1

[extras]
name=CentOS-$releasever - Extras - mirrors.aliyun.com
failovermethod=priority
baseurl=https://mirrors.aliyun.com/centos/$releasever/extras/$basearch/
gpgcheck=1
gpgkey=https://mirrors.aliyun.com/centos/RPM-GPG-KEY-CentOS-7
enabled=1

[centosplus]
name=CentOS-$releasever - Plus - mirrors.aliyun.com
failovermethod=priority
baseurl=https://mirrors.aliyun.com/centos/$releasever/centosplus/$basearch/
gpgcheck=1
gpgkey=https://mirrors.aliyun.com/centos/RPM-GPG-KEY-CentOS-7
enabled=0
EOF

log_success "✅ 已配置 CentOS 基础仓库"

# 配置 EPEL 仓库（如果存在）
if rpm -q epel-release >/dev/null 2>&1; then
    log_info "检测到 EPEL 仓库，配置阿里云 EPEL 镜像..."
    
    # 备份 EPEL 配置
    if [ -f /etc/yum.repos.d/epel.repo ]; then
        cp /etc/yum.repos.d/epel.repo "$BACKUP_SUBDIR/epel.repo.bak" 2>/dev/null || true
    fi
    
    # 配置阿里云 EPEL
    cat > /etc/yum.repos.d/epel.repo <<'EOF'
[epel]
name=Extra Packages for Enterprise Linux 7 - $basearch
baseurl=https://mirrors.aliyun.com/epel/7/$basearch
failovermethod=priority
enabled=1
gpgcheck=1
gpgkey=https://mirrors.aliyun.com/epel/RPM-GPG-KEY-EPEL-7

[epel-debuginfo]
name=Extra Packages for Enterprise Linux 7 - $basearch - Debug
baseurl=https://mirrors.aliyun.com/epel/7/$basearch/debug
failovermethod=priority
enabled=0
gpgkey=https://mirrors.aliyun.com/epel/RPM-GPG-KEY-EPEL-7
gpgcheck=1

[epel-source]
name=Extra Packages for Enterprise Linux 7 - $basearch - Source
baseurl=https://mirrors.aliyun.com/epel/7/SRPMS
failovermethod=priority
enabled=0
gpgkey=https://mirrors.aliyun.com/epel/RPM-GPG-KEY-EPEL-7
gpgcheck=1
EOF
    
    log_success "✅ 已配置 EPEL 仓库"
else
    log_info "未检测到 EPEL 仓库，跳过 EPEL 配置"
fi

# 清理 yum 缓存
log_info "步骤 4/5: 清理并更新 yum 缓存..."
yum clean all >/dev/null 2>&1 || true
log_success "✅ 已清理 yum 缓存"

# 更新 yum 缓存
log_info "正在更新 yum 缓存（这可能需要一些时间）..."
if yum makecache fast >/dev/null 2>&1; then
    log_success "✅ yum 缓存更新成功"
else
    log_warning "⚠️  快速缓存更新失败，尝试完整更新..."
    if yum makecache >/dev/null 2>&1; then
        log_success "✅ yum 缓存更新成功"
    else
        log_error "❌ yum 缓存更新失败"
        log_info "请检查网络连接和镜像源配置"
        exit 1
    fi
fi

# 显示仓库信息
log_info ""
log_info "已配置的仓库列表："
yum repolist enabled | tail -n +2 || true
log_info ""

# 更新系统
log_info "步骤 5/5: 更新系统软件包..."
log_warning "⚠️  这将更新所有可用的软件包，可能需要较长时间"
read -p "是否现在更新系统? (y/N): " -n 1 -r
echo
if [[ $REPLY =~ ^[Yy]$ ]]; then
    log_info "开始更新系统（这可能需要较长时间）..."
    if yum update -y; then
        log_success "✅ 系统更新完成"
    else
        log_error "❌ 系统更新失败"
        exit 1
    fi
else
    log_info "已跳过系统更新"
    log_info "您可以稍后手动运行: sudo yum update -y"
fi

# 完成
log_info ""
log_info "=========================================="
log_success "✅ 配置完成！"
log_info "=========================================="
log_info ""
log_info "配置摘要："
log_info "  - 已备份原有配置到: $BACKUP_SUBDIR"
log_info "  - 已配置阿里云镜像源"
log_info "  - 已更新 yum 缓存"
log_info ""
log_info "常用命令："
log_info "  - 更新系统: sudo yum update -y"
log_info "  - 安装软件: sudo yum install <package>"
log_info "  - 查看仓库: yum repolist"
log_info "  - 恢复备份: 从 $BACKUP_SUBDIR 恢复 .repo 文件"
log_info ""

